﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Xml;

namespace Moonlite.Data.Configuration
{
    /// <summary>
    /// Provides helper methods for converting between types.
    /// </summary>
    internal static class TypeConvertHelpers
    {
        /// <summary>
        /// Converts the name to an instance of the specified type.
        /// </summary>
        /// <typeparam name="T">The type to convert to.</typeparam>
        /// <param name="name">The name.</param>
        /// <returns>The converted name.</returns>
        public static T FromString<T>(string name)
        {
            try
            {
                return (T)Convert.ChangeType(name, typeof(T), CultureInfo.InvariantCulture);
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// Converts the name to an instance of the specified type.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="type">The type to convert to.</param>
        /// <returns>The converted name.</returns>
        public static object FromString(string name, Type type)
        {
            try
            {
                return Convert.ChangeType(name, type, CultureInfo.InvariantCulture);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Converts the given Xml attribute to an instance of the specified type.
        /// </summary>
        /// <typeparam name="T">The type to convert to.</typeparam>
        /// <param name="node">The node.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <returns>The converted attribute.</returns>
        public static T FromXmlAttribute<T>(XmlNode node, string attributeName)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            if (String.IsNullOrEmpty(attributeName))
            {
                throw new ArgumentException("Cannot be null or empty", "attributeName");
            }

            XmlAttribute attribute = node.Attributes[attributeName];
            if (attribute == null)
            {
                return default(T);
            }

            return FromString<T>(attribute.Value);
        }
    }
}
